package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.ShoppingCartDao;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.web.R;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 购物车业务层实现类
 *
 * @Name : ShoppingCartServiceImpl
 * @Author : WuQiang
 * @Date : 2022-08-19 20:30
 * @Description : 购物车业务层实现类
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart>
        implements ShoppingCartService {
    @Override
    public R add(ShoppingCart shoppingCart) {
        //核心业务
        //通过用户id和菜品或者套餐id查询数据库
        Long userId = ThreadLocalUtil.getCurrentId();
        shoppingCart.setUserId(userId);
        //组装查询sql语句
        //判断当前加入购物车的是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        ShoppingCart dbCart = this.getOne(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId)
                .eq(dishId != null, ShoppingCart::getDishId, dishId)
                .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId));


        if (dbCart == null) {
            //第一次加入购物车
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            dbCart = shoppingCart;
        } else {
            //已经在购物车了
            dbCart.setNumber(dbCart.getNumber() + 1);
            this.updateById(dbCart);
        }
        return R.success("添加成功", dbCart);
    }
}
